import React, { FC, useEffect, useState } from 'react';
import { Tag, TreeSelect } from 'antd';
import type { SelectProps, TreeSelectProps } from 'antd';
import { httpPost } from '@utils/HttpUtil';
import { getKnowledgeTree, randomColor } from '@utils/WeStudyUtil';

type TagRender = SelectProps['tagRender'];

const SelectKnowledgeTree: FC<any> = ({ onChange, max, value }) => {
  if(max === undefined || max === null) {
    max = 1; // 默认最大标签数
  }
  const data = getKnowledgeTree();
  const [nodeList, setNodeList] = useState(data);

  const tagRender: TagRender = (props) => {
    const { label, closable, onClose } = props;
    const onPreventMouseDown = (event: React.MouseEvent<HTMLSpanElement>) => {
      event.preventDefault();
      event.stopPropagation();
    };
    if(props === undefined || props.value === undefined) {
      return <></>;
    }
    var item = httpPost("/knowledge/getKnowledgeById", { id: props.value }).data;
    return (
      <Tag
        color={item.color === undefined ? randomColor() : item.color}
        onMouseDown={onPreventMouseDown}
        closable={closable}
        onClose={onClose}
      >
        {item.name}
      </Tag>
    );
  };

  if(value === undefined || value === null) {
    value = [];
  }

  const [nodeValue, setNodeValue] = useState(value);

  const onChangeNode = (value: any) => {
    // alert("选中或移除");
    setNodeValue(value);
    onChange(value);
  };

  const onPopupScroll: TreeSelectProps["onPopupScroll"] = (e) => {
    // alert("滚动");
  };

  const handleDropdownVisibleChange = (visible: any) => {
    if (visible) {
      // 下拉框展开时触发的逻辑
      // alert('下拉树已展开，执行自定义操作');
      // 例如：加载异步数据、更新状态等
      var resData = getKnowledgeTree();
      setNodeList(resData);
    }
  };

  return (
    <div>
      <TreeSelect
        showSearch
        //这一行代码是关键，设置了treeNodeFilterProp属性，可以根据title属性进行搜索
        treeNodeFilterProp="title"
        style={{ width: "100%" }}
        value={nodeValue}
        dropdownStyle={{ maxHeight: 600, overflow: "auto" }}
        onDropdownVisibleChange={handleDropdownVisibleChange}
        placeholder="请选择知识点"
        tagRender={tagRender}
        allowClear
        multiple
        maxTagCount={max}
        onChange={onChangeNode}
        treeData={nodeList}
        onPopupScroll={onPopupScroll}
      />
    </div>
  );
};

export default SelectKnowledgeTree;